/**
 * 页面初始化逻辑：模板及初始化数据的配置及加载
 */
import { getMultiLang } from 'nc-lightapp-front';
import requestApi from './requestApi';
import { setTableExtendCol } from 'ssccommon/components/bill';
import { tableExtendButtonClick } from './events';
import presetVar from './presetVar';
import attachments from 'uap/common/components/getAttachmentInfo';
import { setFormEditableKeys, setAllCardTableEditableKeys } from './utils'

const { getAttachments, getAttachmentsInfo } = attachments;
//import buttonTpl from './buttonTpl';
const head1 = presetVar.head.head1;
const body1 = presetVar.body.body1;
const pageButton = presetVar.pageButton;
const statusVar = presetVar.status;
let alreadyLoadData = false;
let pageStatus = presetVar.pageStatus;
let openBillId = presetVar.openBillId;

export default function (props) {
    

    props.createUIDom(
        {
            pagecode: presetVar.nccPageCode,
            appcode: presetVar.nccAppCode
        },
        async (data) => {
             // 全局化组织汇率类型
            let zzhllxs = data.template.head.items.find((item,index) => {
                return item.attrcode === "zzhllx.rate_category"
            })
            window.presetVar.zzhllxs = zzhllxs && zzhllxs.options
            let meta = data.template;
            let buttonTpl = data.button;
            window.buttonTpl = buttonTpl;
            //来源审批-表头渲染改成card_head
            if(meta.code && meta.code.indexOf('20110ADJUST') > -1) {
                presetVar.head.head2 = 'card_head'
            }

            meta[head1].items.forEach((item) => {
                if (item.itemtype == 'number') {
                    item.placeholder = 0;
                }
            })
            meta[body1].items.forEach((item) => {
                if (item.itemtype == 'number') {
                    item.placeholder = 0;
                }
            })
            meta[body1 + '&childform2'].items.forEach((item) => {
                if (item.itemtype == 'number') {
                    item.placeholder = 0;
                }
            })

            meta[body1 + '&childform1'].items.forEach((item) => {
                if (item.itemtype == 'number') {
                    item.placeholder = 0;
                }
            })
            //动态获取交易类型,优先url获取，否则在应用参数注册获取，不支持页面写死
            let transtype = data.context.paramMap.transtype;

            this.setState({
                title: data.context.paramMap.transtype_name
            })
            presetVar.tradeType = presetVar.tradeType || transtype;

            delete meta.formrelation;
            presetVar.pageId = meta.pageid;
            if (pageStatus == statusVar.browse) {

                //模板处理
                await getAttachmentControl()

                tplHandle.call(this, meta, buttonTpl).then(() => {
                    viewBill.call(this);
                });
            } else { //新增和编辑态需要loaddata
                //加载模板默认数据
                await getAttachmentControl()

                requestApi.loadData({
                    meta: meta,
                    props: props,
                    success: (metas, data) => {
                        alreadyLoadData = true;
                        //模板处理
                        tplHandle.call(this, meta, buttonTpl).then(() => {
                            if (pageStatus == statusVar.add) { //新增态
                                let copyFromBillId = props.getUrlParam('copyFromBillId');
                                if (copyFromBillId) { //如果存在copyFromBillId参数，则执行拷贝单据操作
                                    copyBill(props,copyFromBillId);
                                } else {
                                    props.cardTable.addRow(body1, undefined, undefined, false);
                                    let headData = props.form.getAllFormValue(head1);
                                    shoulderBtnVisibleHandle.call(this,props, headData);
                                }
                            
                            } else if (pageStatus == statusVar.edit) { //编辑态加载数据
                                viewBill.call(this);
                            }
                            setFormEditableKeys(props)
                            setAllCardTableEditableKeys(props, data)
                        });

                    }
                });

            }
        }
    )

    async function viewBill() {
        
        await getAttachmentControl()

        let billdata = {};
        billdata.openbillid = openBillId;
        billdata.tradetype = presetVar.tradeType;
        //billdata.uid = "1001Z3100000000000AE";//这里以后从session中获取
        billdata.pagecode = presetVar.nccPageCode;
        const that = this
        requestApi.viewBill({
            data: billdata,
            success: (data) => {
                props.form.setAllFormValue({ [presetVar.head.head1]: data.head[presetVar.head.head1] });
                //设置表体数据
                Object.values(presetVar.body).forEach((body) => {
                    if (data.bodys[body]) {
                        props.cardTable.setTableDataWithResetInitValue(body, data.bodys[body]);
                    }
                });
                shoulderBtnVisibleHandle.call(that, props, data.head[head1]);
            }
        });
    }

    //处理模板数据
    async function tplHandle(meta, buttonTpl) {
      
        
        //设置表体模板扩展列
        let extendColPromise = await setTableExtendCol(props, meta, buttonTpl,
            [
                {
                    tableAreaId: body1, //表体区域id 
                    // btnAreaId: body1 + '_card_body_inner', //扩展列按钮的区域id，如按照规则配置模板，则无需此配置 
                    /* buttonVisible: (record, index) => { //按钮可见性，如默认全部显示，则无需此配置 
                        return [body1 + '_Delete'] 
                    }, */
                    onButtonClick: tableExtendButtonClick.bind(this), //按钮事件，如仅用默认按钮事件行为，则可以不配置 
                    copyRowWithoutCols: ['pk_cshare_detail']
                }
            ]
        );

        switch (pageStatus) {
            case statusVar.add:
                meta[head1].status = statusVar.add;
                Object.values(presetVar.body).forEach((body) => {
                    if (meta[body]) {
                        meta[body].status = statusVar.add;
                    }
                });
                break;
            case statusVar.edit:
                meta[head1].status = statusVar.edit;
                Object.values(presetVar.body).forEach((body) => {
                    if (meta[body]) {
                        meta[body].status = statusVar.edit;
                    }
                });
                break;
            case statusVar.browse:
                meta[head1].status = statusVar.browse;
                break;
        }

        props.button.hideButtonsByAreas(head1);
        props.button.setButtons(buttonTpl);
        getAttachmentsCount(props)

        //设置页面模板
        props.meta.setMeta(meta, () => {

            console.log('处理后的模板数据3', props.meta.getMeta());

        });
        changeComStatus(props);
        return;

    }
}

function getAttachmentControl() {
    //请求附件控制参数
    return new Promise((resolve, reject) =>{
        requestApi.getAttachmentControlParams({
            data: { transtypecode: presetVar.tradeType },
            success: (data) => {
                // data.enablemodifyaccessory  审批中是否允许修改
                // data.mustuploadaccessory 是否必须上传附件
                window.presetVar.attachmentControl = {
                    modify: data.enablemodifyaccessory,
                    necessary: data.mustuploadaccessory
                }
                resolve()
            }
        })
    })

}

function getAttachmentsCount(props) {
    let multiLang = props.MutiInit.getIntl(2011);
    if (presetVar.openBillId) {
        getAttachments(presetVar.openBillId).then((count) => {
            props.button.setButtonTitle('File', multiLang&&multiLang.get('201102TZFY-0003')/**'附件'**/ + ' ' + String(count) + ' ');
        })
    } else {
        props.button.setButtonTitle('File', multiLang&&multiLang.get('201102TZFY-0003')/**'附件'**/ + ' ' + 0 + ' ');
    }

}

//复制单据
function copyBill(props, copyFromBillId) {
    let param = {};
    param.copyFromBillId = copyFromBillId;
    param.tradetype = presetVar.tradeType;
    param.pagecode = presetVar.nccPageCode;
    requestApi.copyBill({
        data: param,
        success: async (data) => {
            props.form.setAllFormValue({ [head1]: data.head[head1] });
            //设置表体数据
            Object.values(presetVar.body).forEach((body) => {
                if (data.bodys[body]) {
                    props.cardTable.setTableData(body, data.bodys[body]);
                }
            });
            await getAttachmentControl()
            shoulderBtnVisibleHandle.call(this, props, data.head[head1]);
        }
    });
}

//改变表头表体组件的编辑状态
function changeComStatus(props) {
    let bzbm = props.form.getFormItemsValue(head1,'bzbm');
    if(bzbm.value == window.presetVar.zzbwb){//业务单据中的币种与组织本币一致时，汇率及汇率类型不可修改
        props.form.setFormItemsDisabled(head1, {zzhllx:true});
        props.form.setFormItemsDisabled(head1, {bbhl:true});
    }

    let pageStatus = props.getUrlParam('status'); //重新设置状态变量
    let changeStatus = null;
    switch (pageStatus) {
        case statusVar.add:
            changeStatus = statusVar.add;
            break;
        case statusVar.edit:
            changeStatus = statusVar.edit;
            break;
        case statusVar.browse:
            changeStatus = statusVar.browse;
            break;
    }
    props.form.setFormStatus(head1, changeStatus);

    Object.values(presetVar.body).forEach((body) => {
        if (changeStatus == 'add') {
            props.cardTable.setStatus(body, 'edit');
        } else {
            props.cardTable.setStatus(body, changeStatus);
        }
        //props.cardTable.setStatus(body, changeStatus);
    });
}

function shoulderBtnVisibleHandle(props,head) {
    const that = this;
    let btnsVisibleObj = {};

    for (let btnKey in pageButton) {
        btnsVisibleObj[btnKey] = false;
    }
    //肩部按钮可见状态：页面和表格的肩部按钮，这里逻辑根据实际业务实现。
    //let btnsVisibleObj = {};
    let isAddOrEditStatus = pageStatus == statusVar.edit || pageStatus == statusVar.add;
    let isBrowseStatus = pageStatus == statusVar.browse;

    //肩部按钮可见状态：页面和表格的肩部按钮，这里逻辑根据实际业务实现。
    if (isAddOrEditStatus) { //添加或编辑态 显示下列按钮
        btnsVisibleObj[pageButton.Save] = true;
        btnsVisibleObj[pageButton.SaveSubmit] = true;
        btnsVisibleObj[pageButton.File] = true;
        btnsVisibleObj[pageButton.Cancel] = true;
        btnsVisibleObj[body1 + '_Add'] = true;
        btnsVisibleObj[body1 + '_Delete'] = true;
        btnsVisibleObj[body1 + '_Copy'] = true;
        btnsVisibleObj[body1 + '_Insert'] = true;
        btnsVisibleObj['group4'] = false; //更多按钮
        that && that.setState({uploaderBtnDisable: false})
    }

    if (pageStatus == statusVar.edit) {
        // btnsVisibleObj[pageButton.Relation] = true;
        // btnsVisibleObj[pageButton.LinkRelationBill] = true;
    }

    if (isBrowseStatus) { //浏览态 显示下列按钮
        btnsVisibleObj['group4'] = true; //更多按钮 

        btnsVisibleObj[pageButton.Print] = true;
        btnsVisibleObj[pageButton.File] = true;
        btnsVisibleObj[pageButton.ImageShow] = true;
        btnsVisibleObj[pageButton.ImageUpload] = true;
        btnsVisibleObj[body1 + '_Add'] = false;
        btnsVisibleObj[body1 + '_Delete'] = false;
        btnsVisibleObj[body1 + '_Copy'] = false;
        btnsVisibleObj[body1 + '_Insert'] = false;
        btnsVisibleObj[pageButton.Relation] = true;
        btnsVisibleObj[pageButton.LinkRelationBill] = true;

    }
    // btnsVisibleObj[pageButton.pageClose] = true;

    // props.button.setButtonsVisible(btnsVisibleObj);

    //处理数据和按钮状态
    if (head == null || head.rows[0] == null || head.rows[0].values == null)
        return;

    let sxbz = head.rows[0].values.sxbz.value;//单据生效标志
    let spzt = head.rows[0].values.spzt.value;//审批状态
    let djzt = head.rows[0].values.djzt.value//单据状态
    
    if (isBrowseStatus) {
        if (spzt == '-1') { // 审批状态，-1为自由态
            btnsVisibleObj[pageButton.Submit] = true;
            btnsVisibleObj[pageButton.Invalid] = true;
            btnsVisibleObj[pageButton.Copy] = true;
            btnsVisibleObj[pageButton.Edit] = true;
            btnsVisibleObj[pageButton.Delete] = true;
            props.button.setMainButton([pageButton.Submit], true);
        } else if (spzt == '3') { //审批状态为提交状态（3）时 显示收回按钮
            btnsVisibleObj[pageButton.Copy] = true;
            btnsVisibleObj[pageButton.Recall] = true;
            btnsVisibleObj[pageButton.LinkApprovalDetail] = true;
        } else if (spzt == '2') { //审批进行中
            btnsVisibleObj[pageButton.Copy] = true;
            btnsVisibleObj[pageButton.LinkApprovalDetail] = true;
        } else if (sxbz != '1') { //1为已完成单据， 隐藏影响扫描，附件管理。
            if (scene != 'zycx' && scene != 'bzcx' && scene != 'fycx') {
                btnsVisibleObj[pageButton.ImageUpload] = true;
            }
            btnsVisibleObj[pageButton.LinkApprovalDetail] = true;
        }
        
        if (spzt == '-1') { // 审批状态，-1为自由态
            btnsVisibleObj[pageButton.Relation] = true;
            btnsVisibleObj[pageButton.LinkRelationBill] = true;
        } else {
            btnsVisibleObj[pageButton.Relation] = false;
            btnsVisibleObj[pageButton.LinkRelationBill] = false;
        }
        //isShow = sxbz == '1'  && gbzt == '2'; //生效标志已完成（1）， 关闭状态为未关闭（2）的单据显示关闭按钮
        //btnsVisibleObj[pageButton.billClose] = isShow;

        if (djzt == -1) { //作废
            btnsVisibleObj[pageButton.Submit] = false;
            btnsVisibleObj[pageButton.Edit] = false;
            btnsVisibleObj[pageButton.Delete] = false;
            btnsVisibleObj[pageButton.File] = false;
            btnsVisibleObj[pageButton.Invalid] = false;
            btnsVisibleObj[pageButton.ImageUpload] = false;
            btnsVisibleObj[pageButton.Relation] = false;
            btnsVisibleObj[pageButton.LinkRelationBill] = false;
        }
    }

    let scene = props.getUrlParam('scene');
    if (scene == 'zycl' || scene == 'approve' || scene == 'approvesce') {
        btnsVisibleObj[pageButton.Invalid] = false;
        if (isBrowseStatus) {
            if (spzt === '1') {
                btnsVisibleObj[pageButton.Edit] = false;
            } else {
                btnsVisibleObj[pageButton.Edit] = true;
            }
            btnsVisibleObj[pageButton.LinkBudget] = true;
            btnsVisibleObj[pageButton.LinkVoucher] = true;
            btnsVisibleObj[pageButton.LinkApprovalDetail] = true;
            btnsVisibleObj[pageButton.Copy] = false;
            btnsVisibleObj[pageButton.Recall] = false;
            btnsVisibleObj[pageButton.Delete] = false;
            btnsVisibleObj[pageButton.Submit] = false;
            btnsVisibleObj[pageButton.Relation] = false;
            if(spzt == '-1') {
                btnsVisibleObj[pageButton.LinkRelationBill] = false;
            }
        } else {
            btnsVisibleObj[pageButton.SaveSubmit] = false;
        }

    } else if ((scene == 'zycx' || scene == 'bzcx' || scene == 'fycx')) {
        btnsVisibleObj[pageButton.imageShow] = true;
        btnsVisibleObj[pageButton.LinkBudget] = true;
        btnsVisibleObj[pageButton.LinkVoucher] = true;
        btnsVisibleObj[pageButton.LinkApprovalDetail] = true;
        btnsVisibleObj[pageButton.pagePrint] = true;
        btnsVisibleObj[pageButton.billView] = true;
        btnsVisibleObj[pageButton.billApprove] = true;
        btnsVisibleObj[pageButton.fileManager] = true;
        btnsVisibleObj[pageButton.Edit] = false;
        btnsVisibleObj[pageButton.Copy] = false;
        btnsVisibleObj[pageButton.Recall] = false;
        btnsVisibleObj[pageButton.Submit] = false;
        btnsVisibleObj[pageButton.Delete] = false;
        btnsVisibleObj[pageButton.ImageUpload] = false;
        btnsVisibleObj[pageButton.Invalid] = false;
        btnsVisibleObj[pageButton.Relation] = false;
    }

    //来源于报表联查的单据
    if (scene == 'sscermlink' || scene == 'lc') {
        for (let btnKey in pageButton) {
            if (btnKey == pageButton.imageShow || btnKey == pageButton.pagePrint || btnKey === pageButton.fileManager || 
                btnKey == pageButton.LinkBudget || btnKey == pageButton.LinkVoucher 
            ) {
                btnsVisibleObj[btnKey] = isBrowseStatus;
            } else {
                btnsVisibleObj[btnKey] = false;
            }
        }
    }
    // btnsVisibleObj[pageButton.Relation] = true;
    // btnsVisibleObj[pageButton.LinkRelationBill] = true;
    if( scene =='bz' ) {
        btnsVisibleObj[pageButton.LinkApprovalDetail] = isBrowseStatus
    }
    if(isBrowseStatus) {
        btnsVisibleObj[pageButton.LinkBudget] = true;
        btnsVisibleObj[pageButton.LinkVoucher] = true;
    }
    // 审批进行中  提交状态 附件可编辑受控
    if (spzt == 2 || spzt == 3) {
    if (window.presetVar.attachmentControl) {
        that && that.setState({uploaderBtnDisable: !window.presetVar.attachmentControl.modify})
    }
    }else if(spzt == -1) {
        //单据不在审批中,默认可修改
        that && that.setState({uploaderBtnDisable: false})
    }
    if(spzt=='1'){
        btnsVisibleObj["pageMakebill"] = true;//审批中心的制单按钮
        btnsVisibleObj[pageButton.ImageUpload] = false;
        that && that.setState({uploaderBtnDisable: true})

    }else{
        btnsVisibleObj["pageMakebill"] = false;//审批中心的制单按钮
    }
    props.button.setButtonsVisible(btnsVisibleObj);
}

export {shoulderBtnVisibleHandle} 

function routeChange(props){
    pageStatus = props.getUrlParam('status'); //重新设置状态变量
    openBillId = props.getUrlParam('id'); //重设单据id
    presetVar.openBillId = openBillId;
    presetVar.pageStatus = pageStatus;

    switch (pageStatus) {
        case statusVar.browse:
            break;
        case statusVar.add:
        case statusVar.edit:
            //只有以添加/编辑态打开单据时，才会在初始化函数中调用loadData请求，所以如果从浏览态直接打开页面时，是不会加载loaddata的，所以如果页面此时从浏览态转到添加/编辑态，需要加载loadData
            if (!alreadyLoadData) {
                requestApi.loadData({
                    meta: props.meta.getMeta(),
                    props: props,
                    success: (meta) => {
                        alreadyLoadData = true;
                        props.meta.setMeta(meta);
                    }
                })
            }
            break;
    }

    //浏览态不显示表体扩展列
    // Object.values(presetVar.body).forEach((body) => {
    //     if (isShowTableExtCol) {
    //         props.cardTable.showColByKey(body, 'opr'); //显示扩展列
    //     } else {
    //         props.cardTable.hideColByKey(body, 'opr'); //隐藏扩展列
    //     }
    // });

    let copyFromBillId = props.getUrlParam('copyFromBillId');
    if (copyFromBillId) {
        copyBill.call(this, props, copyFromBillId); //复制单据。 因为复制单据操作 既能在初始态触发，又可以被交互态触发。所以没有把该函数写在按钮事件上。
    } else {
        let headData = props.form.getAllFormValue(head1);
        //根据单据状态，改变按钮的显示的状态
        shoulderBtnVisibleHandle.call(this,props,headData);
    }
    getAttachmentsCount.call(this, props)
    //改变平台组件可编辑状态
    changeComStatus(props);
}
export {routeChange}